package servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;


import persistence.Axdbv4HibernateManager;

import domain.RepresentationsNamesRecord;

public class AutoCompleteServlet extends HttpServlet {

	/**
	 * Servlet che si occupa di far funzionare l'autocomplete
	 * 
	 * Data una stringa 'aaaa' ritorna i nomi presenti in representationsName che iniziano
	 * con tale stringa
	 */
	private static final long serialVersionUID = 1L;

	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		resp.setContentType("text/html; charset=UTF-8");
		this.doGet(req, resp);
	}
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		
		PrintWriter out = resp.getWriter();
		resp.setContentType("text/html; charset=UTF-8");
        resp.setHeader("Cache-control", "no-cache, no-store");
        resp.setHeader("Pragma", "no-cache");
        resp.setHeader("Expires", "-1");
  
        
        String query = req.getParameter("term");
      
        System.out.print("AutoCompleteServlet cerca nomi con: "+query);
        
    //    JSONObject json=new JSONObject();
        JSONArray jsonArray=new JSONArray();
        int i=0;
        for (RepresentationsNamesRecord r : getRecordByString(query)) {
        	
        	JSONObject json=new JSONObject();
 //       	json.put(r.getNID(),r.getValue());
        	json.put("NID",r.getNID());
        	json.put("Value", r.getValue());
        	jsonArray.add(json);
        	i++;
        //	System.out.println("\t"+r.getValue());
		}
       System.out.print(" ("+i+" nomi trovati)\n");
      
      //  System.out.println("Formato json ritornato dal server:\n\t"+jsonArray.toString());
        out.println(jsonArray.toString());
        out.close();
       
	}
	
	private List<RepresentationsNamesRecord> getRecordByString(String query){
		List<RepresentationsNamesRecord> result=new ArrayList<RepresentationsNamesRecord>();
		result=Axdbv4HibernateManager.getIstance().getRepresentationNameListByString(query);
		return result;
	}
	
}
